<template>
  <div
    ref="scrollContainer"
    class="scroll-container"
    @scroll="handleScroll"
  >
    <section class="page">
      <Introduce-page @showNext="NextPage" />
    </section>
    <section class="page">
      <Project-page ref="ProjectPage" />
    </section>
    <section class="page">
      <Blog-page />
    </section>
  </div>
</template>

<script>
import IntroducePage from '@/components/IntroducePage.vue';
import ProjectPage from '@/components/ProjectPage.vue';
import BlogPage from '@/components/BlogPage.vue'
import { mapMutations } from 'vuex'

export default {
  components: { IntroducePage, ProjectPage, BlogPage },
  data() {
      return {
          isProgrammaticScroll: false, 
          scrollTimer: null,
          scrollDebounceTimer: null  
      };
  },
  computed: {
    currentPage() {
      return this.$store.state.home.currentPage;
    }
  },
  watch: {
    currentPage(newVal) {
      this.$nextTick(() => {
        const container = this.$refs.scrollContainer;
        const sections = container.querySelectorAll('.page');
        this.isProgrammaticScroll = true;
        if (sections[newVal]) {
          container.scrollTo({
            top: sections[newVal].offsetTop,
            behavior: 'smooth'
          });
        }
        
        // 根据当前页面是否为项目页面来启用或禁用背景效果
        if (newVal === 1) { // 项目页面索引为1
          // 启用项目背景效果
          if (this.$refs.ProjectPage && typeof this.$refs.ProjectPage.enableBackground === 'function') {
            this.$refs.ProjectPage.enableBackground();
          }
        } else {
          // 禁用项目背景效果
          if (this.$refs.ProjectPage && typeof this.$refs.ProjectPage.disableBackground === 'function') {
            this.$refs.ProjectPage.disableBackground();
          }
        }
        
        if (this.scrollTimer) clearTimeout(this.scrollTimer);
        this.scrollTimer = setTimeout(() => {
          this.isProgrammaticScroll = false;
        }, 50);
      });
    }
  },
  methods: {
    ...mapMutations('home', ['setCurrentPage']),
    handleScroll(e) {
      if (this.scrollDebounceTimer) clearTimeout(this.scrollDebounceTimer);
      
      this.scrollDebounceTimer = setTimeout(() => {
        if (this.isProgrammaticScroll) return;
        const scrollTop = e.target.scrollTop;

        // 获取所有section
        const container = this.$refs.scrollContainer;
        const sections = container.querySelectorAll('.page');

        // 计算最接近的页面
        let closestPage = 0;
        let smallestDistance = Math.abs(scrollTop - sections[0].offsetTop);
        
        for (let i = 1; i < sections.length; i++) {
          const distance = Math.abs(scrollTop - sections[i].offsetTop);
          if (distance < smallestDistance) {
            smallestDistance = distance;
            closestPage = i;
          }
        }

        // 只有当最接近的页面发生变化时才更新currentPage
        if (closestPage !== this.currentPage) {
          this.setCurrentPage(closestPage);
        }
      }, 50); 
    },
    NextPage() {
      this.setCurrentPage(1);
    },
    handleKeydown(e) {
        if (e.code === 'Space' || e.key === ' ') {
          this.setCurrentPage(this.currentPage + 1);
          e.preventDefault();
        }
    },
    handleResize() {
      this.$nextTick(() => {
        const container = this.$refs.scrollContainer;
        if (!container) return;
        
        const scrollTop = container.scrollTop;
        const sections = container.querySelectorAll('.page');
        
        if (sections.length === 0) return;
        
        // 计算最接近的页面
        let closestPage = 0;
        let smallestDistance = Math.abs(scrollTop - sections[0].offsetTop);
        
        for (let i = 1; i < sections.length; i++) {
          const distance = Math.abs(scrollTop - sections[i].offsetTop);
          if (distance < smallestDistance) {
            smallestDistance = distance;
            closestPage = i;
          }
        }
        // 直接滚动到目标页面
        this.isProgrammaticScroll = true;
        if (sections[closestPage]) {
          container.scrollTo({
            top: sections[closestPage].offsetTop,
            behavior: 'auto'
          });
        }
        // 更新当前页面
        this.setCurrentPage(closestPage);
        // 重置滚动标志
        if (this.scrollTimer) clearTimeout(this.scrollTimer);
        this.scrollTimer = setTimeout(() => {
          this.isProgrammaticScroll = false;
        }, 100);
      });
    },
    // 初始化滚动位置
    initializeScrollPosition() {
      this.$nextTick(() => {
        const container = this.$refs.scrollContainer;
        const sections = container.querySelectorAll('.page');
        
        if (sections.length > this.currentPage && sections[this.currentPage]) {
          // 立即滚动到正确位置，不使用动画
          container.scrollTo({
            top: sections[this.currentPage].offsetTop,
            behavior: 'auto'
          });
        }
      });
    }
  },
  mounted(){
      // 检查是否是页面刷新
      if (performance.navigation.type === 1) { // 1 表示页面刷新
        // 同时更新Vuex中的状态
        this.setCurrentPage(0);
      }
      window.addEventListener('keydown', this.handleKeydown);
      window.addEventListener('resize', this.handleResize);
      
      // 组件挂载时，立即初始化滚动位置
      this.initializeScrollPosition();
  },
  beforeUnmount(){
    window.removeEventListener('keydown', this.handleKeydown);
    window.removeEventListener('resize', this.handleResize);
    if (this.scrollTimer) clearTimeout(this.scrollTimer);
    if (this.scrollDebounceTimer) clearTimeout(this.scrollDebounceTimer);
  }
};
</script>

<style>
.scroll-container {
  height: 100vh;
  overflow-y: scroll;
  /* 隐藏滚动条但保持滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/* 隐藏 Webkit 浏览器的滚动条 */
.scroll-container::-webkit-scrollbar {
  display: none;
}

.page {
  height: 100vh;
  position: relative;
  overflow: hidden; 
}
</style>